package com.maixy.studyonlineapi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maixy.studyonlineapi.bean.Page;
import com.maixy.studyonlineapi.bean.SessionUser;
import com.maixy.studyonlineapi.entity.Activity;
import com.maixy.studyonlineapi.entity.Manager;
import com.maixy.studyonlineapi.entity.Media;
import com.maixy.studyonlineapi.entity.Moment;
import com.maixy.studyonlineapi.entity.Team;
import com.maixy.studyonlineapi.entity.User;
import com.maixy.studyonlineapi.entity.ViolationRecord;
import com.maixy.studyonlineapi.enums.ActivityViewTypeEnum;
import com.maixy.studyonlineapi.exceptions.TipException;
import com.maixy.studyonlineapi.mapper.ActivityMapper;
import com.maixy.studyonlineapi.mapper.ManagerMapper;
import com.maixy.studyonlineapi.mapper.MomentMapper;
import com.maixy.studyonlineapi.mapper.UserMapper;
import com.maixy.studyonlineapi.result.PageData;
import com.maixy.studyonlineapi.utils.DataTypeUtil;
import com.maixy.studyonlineapi.utils.JwtUtils;
import com.maixy.studyonlineapi.utils.LocalDateTimeUtils;
import com.maixy.studyonlineapi.view.ActivityView;
import com.maixy.studyonlineapi.view.ManagerBasisInfoView;
import com.maixy.studyonlineapi.view.ManagerView;
import com.maixy.studyonlineapi.view.MomentView;
import com.maixy.studyonlineapi.view.UserView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName ManagerService
 * @Description TODO
 * @Date 2021/3/4 16:40
 * @Author maixy
 */
@Service
public class ManagerService extends BaseMPlusService<Manager, Long>{

    private final ManagerMapper managerMapper;

    @Resource
    public MediaService mediaService;

    @Resource
    public ActivityMapper activityMapper;

    @Resource
    private ActivityService activityService;

    @Resource
    private ViolationRecordService violationRecordService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private TeamService teamService;

    @Resource
    private AuthService authService;

    @Resource
    private MomentService momentService;

    @Resource
    private MomentMapper momentMapper;

    protected ManagerService(ManagerMapper managerMapper) {
        super(Manager.class, managerMapper);
        this.managerMapper = managerMapper;
    }

    /**
     * 根据用户名和密码查询用户
     * @param userName 用户名
     * @param pwd 密码
     * @return com.maixy.studyonlineapi.entity.User
     */
    public Manager findManagerByUserNameAndPwd(String userName, String pwd) {
        return managerMapper.selectOne(new QueryWrapper<Manager>()
                .lambda()
                .eq(Manager::getUserName, userName)
                .eq(Manager::getPwd, pwd)
                .eq(Manager::getHasDelete, false)
                .orderByDesc(Manager::getCreateTime)
                .last("limit 1"));
    }

    /**
     * 根据用户名和密码查询用户
     * @param userName 用户名
     * @return com.maixy.studyonlineapi.entity.User
     */
    public Manager findManagerByUserName(String userName) {
        return managerMapper.selectOne(new QueryWrapper<Manager>()
                .lambda()
                .eq(Manager::getUserName, userName)
                .eq(Manager::getHasDelete, false)
                .orderByDesc(Manager::getCreateTime)
                .last("limit 1"));
    }

    /**
     * 生成用户Session
     * @param manager 运维人员实体类
     * @return com.maixy.studyonlineapi.bean.SessionUser
     */
    public SessionUser buildManagerInfo(Manager manager) {
        if (null == manager || manager.getHasDelete()) {
            throw new TipException("用户不存在或已被删除");
        }
        SessionUser sessionUser = new SessionUser();
        Media media = mediaService.findById(manager.getAvatarId());
        if (null == media || media.getHasDelete()) {
            throw new TipException("找不到头像信息");
        }
        String sessionId = JwtUtils.createToken(manager.getId(), manager.getUserName(), manager.getNickName(), media.getMediaUrl());
        sessionUser.setSessionId(sessionId);
        sessionUser.setUserId(String.valueOf(manager.getId()));
        sessionUser.setUserName(manager.getUserName());
        sessionUser.setNickName(manager.getNickName());
        sessionUser.setAvatarUrl(media.getMediaUrl());
        return sessionUser;
    }


    /**
     * 用户基本信息
     *
     * @param userId 用户id
     */
    public ManagerBasisInfoView getManagerBasisInfo(Long userId) {
        ManagerBasisInfoView view = new ManagerBasisInfoView();
        Manager manager = findById(userId);
        if (null == manager || manager.getHasDelete()) {
            throw new TipException("用户不存在或已被删除");
        }
        view.setType(manager.getType());
        return view;
    }

    public PageData<ActivityView> getActivityList(String activitySearch, Integer activityType, Integer activityStatus, Page page) {
        page.setHasMore(false);
        PageData<ActivityView> pageData = new PageData<>();
        pageData.setPage(page);
        pageData.setData(Collections.emptyList());
        int beginIndex = (page.getPage() - 1) * page.getSize();
        if (StringUtils.isNoneBlank(activitySearch)) {
            activitySearch = "%".concat(activitySearch).concat("%");
        }
        List<Activity> activityList = activityMapper.getActivityList(activitySearch, activityType, activityStatus, beginIndex, page.getSize() + 1);
        if (CollectionUtils.isEmpty(activityList)) {
            return pageData;
        }
        if (activityList.size() > page.getSize()) {
            page.setHasMore(true);
            activityList.remove(activityList.size() - 1);
        }

        List<ActivityView> activityViewList = new ArrayList<>();
        for (Activity activity : activityList) {
            ActivityView view = activityService.convert(activity, null, null, ActivityViewTypeEnum.TEACHER.getId());
            ViolationRecord violationRecord = violationRecordService.findByTypeAndEntityId(1, activity.getId());
            if (null == violationRecord) {
                view.setActivityStatus(1);
            } else {
                view.setActivityStatus(2);
            }
            activityViewList.add(view);
        }
        pageData.setData(activityViewList);

        return pageData;
    }


    public void setViolation(Long activityId, Integer type, Long managerId) {
        Manager manager = findById(managerId);
        if (null == manager || manager.getHasDelete()) {
            throw new TipException("没有权限");
        }
        ViolationRecord record = violationRecordService.findByTypeAndEntityId(type, activityId);
        if (null == record || record.getHasDelete()) {
            record = new ViolationRecord();
            record.setCreateBy(managerId);
            record.setCreateTime(System.currentTimeMillis());
            record.setHasDelete(false);
            record.setEntityId(activityId);
            record.setType(type);
            violationRecordService.create(record);
        } else {
            record.setUpdateBy(managerId);
            record.setCreateTime(System.currentTimeMillis());
            record.setHasDelete(true);
            violationRecordService.update(record);
        }
    }

    public PageData<UserView> getUserList(String nickNameSearch, Page page) {
        page.setHasMore(false);
        PageData<UserView> pageData = new PageData<>();
        pageData.setPage(page);
        pageData.setData(Collections.emptyList());
        int beginIndex = (page.getPage() - 1) * page.getSize();
        if (StringUtils.isNoneBlank(nickNameSearch)) {
            nickNameSearch = "%".concat(nickNameSearch).concat("%");
        }
        List<User> userList = userMapper.getUserList(nickNameSearch, beginIndex, page.getSize() + 1);
        if (CollectionUtils.isEmpty(userList)) {
            return pageData;
        }
        if (userList.size() > page.getSize()) {
            page.setHasMore(true);
            userList.remove(userList.size() - 1);
        }

        List<UserView> userViewArrayList = new ArrayList<>();
        for (User user : userList) {
            UserView userView = (userService.convert(user));
            Team team = teamService.findTeamByUserId(user.getId());
            if (null == team || team.getHasDelete()) {
                userView.setTeamUserCount(0);
            } else {
                userView.setTeamUserCount(teamUserService.countTeamUser(team.getId()));
            }
            userView.setUserName(user.getUserName());
            userView.setActivityNum(activityService.countActivity(user.getId()));
            userView.setJoinActivityNum(authService.countAuthNum(user.getId()));
            userViewArrayList.add(userView);
        }
        pageData.setData(userViewArrayList);

        return pageData;
    }

    public PageData<ManagerView> getManagerList(String userNameSearch, Page page) {
        page.setHasMore(false);
        PageData<ManagerView> pageData = new PageData<>();
        pageData.setPage(page);
        pageData.setData(Collections.emptyList());
        int beginIndex = (page.getPage() - 1) * page.getSize();
        if (StringUtils.isNoneBlank(userNameSearch)) {
            userNameSearch = "%".concat(userNameSearch).concat("%");
        }
        List<Manager> managerList = managerMapper.getManagerList(userNameSearch, beginIndex, page.getSize() + 1);
        if (CollectionUtils.isEmpty(managerList)) {
            return pageData;
        }
        if (managerList.size() > page.getSize()) {
            page.setHasMore(true);
            managerList.remove(managerList.size() - 1);
        }

        List<ManagerView> managerViewList = new ArrayList<>();
        for (Manager manager : managerList) {
            ManagerView view = new ManagerView();
            view.setManagerId(DataTypeUtil.getStr(manager.getId()));
            view.setType(manager.getType());
            view.setUserName(manager.getUserName());
            Media media = mediaService.findById(manager.getAvatarId());
            if (null == media || media.getHasDelete()) {
                throw new TipException("找不到头像信息");
            }
            view.setAvatarUrl(media.getMediaUrl());
            managerViewList.add(view);
        }
        pageData.setData(managerViewList);
        return pageData;
    }

    public void addManager(String userName, String pwd, Long managerId) {
        Manager superManager = findById(managerId);
        if (null == superManager || superManager.getHasDelete() || 1 != superManager.getType()) {
            throw new TipException("没有权限");
        }

        Manager manager = findManagerByUserName(userName);
        if (null != manager && !manager.getHasDelete()) {
            throw new TipException("用户名已经存在");
        }
        manager =new Manager();
        manager.setCreateBy(managerId);
        manager.setCreateTime(System.currentTimeMillis());
        manager.setHasDelete(false);
        manager.setType(2);
        manager.setUserName(userName);
        manager.setPwd(pwd);
        manager.setNickName(userName);
        manager.setAvatarId(1L);
        create(manager);

    }

    public void updateManager(Long currentManagerId, Long managerId) {
        Manager superManager = findById(managerId);
        if (null == superManager || superManager.getHasDelete() || 1 != superManager.getType()) {
            throw new TipException("没有权限");
        }

        Manager manager = findById(currentManagerId);
        if (null == manager || manager.getHasDelete()) {
            throw new TipException("用户不存在");
        }

        if (currentManagerId.equals(managerId)) {
            throw new TipException("不能修改自己的权限");
        }

        manager.setUpdateBy(managerId);
        manager.setUpdateTime(System.currentTimeMillis());
        manager.setHasDelete(true);
        update(manager);
    }

    public PageData<MomentView> getMomentList(String momentSearch, Integer momentStatus, Page page) {
        page.setHasMore(false);
        PageData<MomentView> pageData = new PageData<>();
        pageData.setPage(page);
        pageData.setData(Collections.emptyList());
        int beginIndex = (page.getPage() - 1) * page.getSize();
        if (StringUtils.isNoneBlank(momentSearch)) {
            momentSearch = "%".concat(momentSearch).concat("%");
        }
        List<Moment> momentList = momentMapper.findV2MomentList(momentSearch, momentStatus,
                beginIndex, page.getSize() + 1);
        if (CollectionUtils.isEmpty(momentList)) {
            return pageData;
        }
        if (momentList.size() > page.getSize()) {
            page.setHasMore(true);
            momentList.remove(momentList.size() - 1);
        }

        List<MomentView> momentViewList = new ArrayList<>();
        for (Moment moment : momentList) {
            MomentView view = new MomentView();
            User user = userService.findById(moment.getCreateBy());
            if (null == user || user.getHasDelete()) {
                continue;
            }
            view.setMomentId(DataTypeUtil.getStr(moment.getId()));
            view.setUserView(userService.convert(user));
            view.setCreateTimeStr(LocalDateTimeUtils.format(moment.getCreateTime(), LocalDateTimeUtils.NORMAL_DATETIME_FORMAT_NO_SECOND));
            view.setContent(moment.getContent());
            Activity activity = activityService.findById(moment.getActivityId());
            if (null == activity || activity.getHasDelete()) {
                continue;
            }
            view.setActivityView(activityService.convert(activity, null , null, ActivityViewTypeEnum.TEACHER.getId()));
            ViolationRecord violationRecord = violationRecordService.findByTypeAndEntityId(2, moment.getId());
            if (null == violationRecord) {
                view.setMomentStatus(1);
            } else {
                view.setMomentStatus(2);
            }
            momentViewList.add(view);
        }
        pageData.setData(momentViewList);
        return pageData;
    }

}
